package models

import (
	"errors"
	//"fmt"

	"fmt"
	"log"

	//"time"

	//"strconv"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/validation"
)

type Urldeny struct {
	Id          int64  `json:"id"`
	Appname     string `json:"appname" valid:"Required"`
	Deny_host   string `json:"deny_host"`
	Deny_url    string `json:"deny_url" valid:"Required"`
	Deny_type   string `json:"deny_type"`
	Deny_key    string `json:"deny_key"`
	Deny_enable bool   `json:"deny_enable"`
	Remarks     string `json:"remarks"`
	Updatetime  string `json:"updatetime"`
	Createtime  string `json:"createtime"`
}

func init() {
	orm.Debug = true
	//orm.RegisterModel(new(Limitrule)) //因为configModel中已注册，无法重复注册，即使更改结构体名称
}

func (u *Urldeny) TableName() string {
	return "xf_waf_urldeny"
}

func check_xud(u *Urldeny) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

//List
func GetList_UrlDeny(appname string, id int64) (xlr []*Urldeny, count int64) {
	o := orm.NewOrm()
	var sqlstr string
	if id > 0 {
		sqlstr = fmt.Sprintf("select * from xf_waf_urldeny where id = '%d'", id)
	}
	if appname != "" {
		sqlstr = fmt.Sprintf("select * from xf_waf_urldeny where appname = '%s' ORDER BY id", appname)
	}
	num, err2 := o.Raw(sqlstr).QueryRows(&xlr)
	if err2 != nil {
		log.Println(err2)
	}
	return xlr, num
}

//添加
func Add_UrlDeny(u *Urldeny) (int64, error) {
	if err := check_xud(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	var numt int64
	res, err := o.Raw(`insert into xf_waf_urldeny(appname,deny_host,deny_url,deny_type,deny_key,remarks)values(?,?,?,?,?,?)`, u.Appname, u.Deny_host, u.Deny_url, u.Deny_type, u.Deny_key, u.Remarks).Exec()
	if err != nil {
		log.Printf("[ERROR] Add UrlDeny err:%s\n", err)
		return 0, err
	}
	Id, _ := res.LastInsertId()
	if Id > 0 {
		numt++
	}
	UpdateConfigTime(u.Appname)
	return numt, nil
}

func DelUrlDenyById(id int64, appname string) (int64, error) {
	o := orm.NewOrm()
	res, err := o.Raw(`DELETE FROM xf_waf_urldeny WHERE id = ?`, id).Exec()
	if err != nil {
		log.Printf("[ERROR] Del UrlDeny err:%s\n", err)
		return 0, err
	}
	num, err := res.RowsAffected()
	if err != nil {
		log.Printf("[ERROR] Del UrlDenyFail3 err:%s\n", err)
		return 0, err
	}
	UpdateConfigTime(appname)
	return num, nil
}

func EditUrlDeny(id, appname, key, value string) (int64, error) {
	o := orm.NewOrm()
	sqlstr := fmt.Sprintf("UPDATE xf_waf_urldeny SET %s = '%s' WHERE id = %s AND appname = '%s'", key, value, id, appname)
	res, err := o.Raw(sqlstr).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Printf("[INFO] EditUrlDeny affected nums:%d\n", num)
		UpdateConfigTime(appname)
		return num, nil
	}
	return 0, err
}
